﻿using System.Linq;
using Axium.DataAccess;
using Axium.Contracts.Data;
using Axium.Contracts.Services;
using AutoMapper;
using System.ServiceModel;
using Axium.Services.Behavior;
using System.Security.Permissions;

namespace Axium.Services
{
    /// <summary>
    /// Concrete service implementation. You busness logig could come here.
    /// AutomapServiceBehavior is just for setup automapper. You you map domain to data contact manualy you do not need this.
    /// </summary>
    [AutomapServiceBehavior]
    public class SomeService : ISomeService
    {
        /// <summary>
        /// Hold a reference to repository as abstraction
        /// </summary>
        private IAxiumRepository _repository;
        /// <summary>
        /// Here is the place for DI. To simplify I just harcode creation of default repository
        /// How it is used you could see from Unit test project
        /// </summary>
        public IAxiumRepository Repository
        {
            get
            {
                if (_repository==null)
                {
                    _repository = new DefaultAxiumRepository();
                }                    
                return _repository;
            }
            set { _repository = value; }
        }
        #region ISomeService Members
        /// <summary>
        /// Allows only Administrators roles
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
        public SomeItemsResponse GetAllItems(SomeItemsRequest request)
        {
            return new SomeItemsResponse
                       {
                           Items = Repository.GetItems(request.Filter).Select(x=> Mapper.Map(x,new SomeItem())).ToArray()
                       };
        }
        public SomeItemResponse GetItem(SomeItemRequest request)
        {
            var item = Repository.GetItem(request.Id);
            return new SomeItemResponse
                       {
                           Item = item == null ? null : Mapper.Map(item, new SomeItem())
                       };
        }

        /// <summary>
        /// Some extra method to thow echeption to show how to log unhandler exceptions.
        /// </summary>
        public void ThrowExeption()
        {
            throw new System.NotImplementedException();
        }

        #endregion

    }
}
